package com.mockapi.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mockapi.common.CommonResult;
import com.mockapi.dto.ResponseTemplateRequest;
import com.mockapi.dto.RouteRequest;
import com.mockapi.entity.ApiLog;
import com.mockapi.entity.ResponseTemplate;
import com.mockapi.entity.Route;
import com.mockapi.service.ApiLogService;
import com.mockapi.service.EventService;
import com.mockapi.service.ResponseTemplateService;
import com.mockapi.service.RouteService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final RouteService routeService;
    private final ResponseTemplateService responseTemplateService;
    private final ApiLogService apiLogService;
    private final EventService eventService;

    // ==================== 路由管理 ====================

    /**
     * 分页查询路由
     */
    @GetMapping("/routes")
    public CommonResult<Page<Route>> getRoutes(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String path,
            @RequestParam(required = false) String method) {
        
        Page<Route> page = routeService.page(pageNum, pageSize, name, path, method);
        return CommonResult.success(page);
    }

    /**
     * 获取路由详情
     */
    @GetMapping("/routes/{id}")
    public CommonResult<Route> getRoute(@PathVariable Long id) {
        Route route = routeService.getById(id);
        return CommonResult.success(route);
    }

    /**
     * 创建路由
     */
    @PostMapping("/routes")
    public CommonResult<Route> createRoute(@Valid @RequestBody RouteRequest request) {
        Route route = new Route();
        BeanUtils.copyProperties(request, route);
        
        boolean success = routeService.save(route);
        if (success) {
            return CommonResult.success(route);
        } else {
            return CommonResult.error("创建失败");
        }
    }

    /**
     * 更新路由
     */
    @PutMapping("/routes/{id}")
    public CommonResult<Route> updateRoute(@PathVariable Long id, @Valid @RequestBody RouteRequest request) {
        Route route = new Route();
        BeanUtils.copyProperties(request, route);
        route.setId(id);
        
        boolean success = routeService.update(route);
        if (success) {
            return CommonResult.success(route);
        } else {
            return CommonResult.error("更新失败");
        }
    }

    /**
     * 删除路由
     */
    @DeleteMapping("/routes/{id}")
    public CommonResult<Void> deleteRoute(@PathVariable Long id) {
        boolean success = routeService.delete(id);
        if (success) {
            return CommonResult.success();
        } else {
            return CommonResult.error("删除失败");
        }
    }

    // ==================== 模板管理 ====================

    /**
     * 分页查询模板
     */
    @GetMapping("/templates")
    public CommonResult<Page<ResponseTemplate>> getTemplates(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name) {
        
        Page<ResponseTemplate> page = responseTemplateService.page(pageNum, pageSize, name);
        return CommonResult.success(page);
    }

    /**
     * 获取所有模板（不分页）
     */
    @GetMapping("/templates/all")
    public CommonResult<List<ResponseTemplate>> getAllTemplates() {
        List<ResponseTemplate> templates = responseTemplateService.list();
        return CommonResult.success(templates);
    }

    /**
     * 获取模板详情
     */
    @GetMapping("/templates/{id}")
    public CommonResult<ResponseTemplate> getTemplate(@PathVariable Long id) {
        ResponseTemplate template = responseTemplateService.getById(id);
        return CommonResult.success(template);
    }

    /**
     * 创建模板
     */
    @PostMapping("/templates")
    public CommonResult<ResponseTemplate> createTemplate(@Valid @RequestBody ResponseTemplateRequest request) {
        ResponseTemplate template = new ResponseTemplate();
        BeanUtils.copyProperties(request, template);
        
        boolean success = responseTemplateService.save(template);
        if (success) {
            return CommonResult.success(template);
        } else {
            return CommonResult.error("创建失败");
        }
    }

    /**
     * 更新模板
     */
    @PutMapping("/templates/{id}")
    public CommonResult<ResponseTemplate> updateTemplate(@PathVariable Long id, @Valid @RequestBody ResponseTemplateRequest request) {
        ResponseTemplate template = new ResponseTemplate();
        BeanUtils.copyProperties(request, template);
        template.setId(id);
        
        boolean success = responseTemplateService.update(template);
        if (success) {
            return CommonResult.success(template);
        } else {
            return CommonResult.error("更新失败");
        }
    }

    /**
     * 删除模板
     */
    @DeleteMapping("/templates/{id}")
    public CommonResult<Void> deleteTemplate(@PathVariable Long id) {
        boolean success = responseTemplateService.delete(id);
        if (success) {
            return CommonResult.success();
        } else {
            return CommonResult.error("删除失败");
        }
    }

    // ==================== 日志管理 ====================

    /**
     * 分页查询日志
     */
    @GetMapping("/logs")
    public CommonResult<Page<ApiLog>> getLogs(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String requestPath,
            @RequestParam(required = false) String requestMethod,
            @RequestParam(required = false) Integer responseStatus,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        
        Page<ApiLog> page = apiLogService.page(pageNum, pageSize, requestPath, requestMethod, responseStatus, startTime, endTime);
        return CommonResult.success(page);
    }

    /**
     * 清理日志
     */
    @DeleteMapping("/logs")
    public CommonResult<Integer> cleanLogs(@RequestParam(defaultValue = "30") Integer days) {
        int count = apiLogService.cleanOldLogs(days);
        return CommonResult.success(count);
    }

    // ==================== 系统统计 ====================

    /**
     * 获取系统统计信息
     */
    @GetMapping("/stats")
    public CommonResult<Map<String, Object>> getStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("routeCount", routeService.getCount());
        stats.put("templateCount", responseTemplateService.getCount());
        stats.put("logCount", apiLogService.getTodayLogCount());
        stats.put("eventCount", eventService.getCount());
        
        return CommonResult.success(stats);
    }
} 